package com.example.android.story.Utils;

import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.LiveData;
import android.support.annotation.NonNull;

import java.util.List;

import cn.bmob.v3.Bmob;

/**
 * Created by liwei on 2018/5/22.
 */

public class StoryViewModel extends AndroidViewModel {
    private StoryRepository repository;
    private LiveData<List<User>> allUsers;
    private LiveData<List<Story>> allStories;

    public StoryViewModel(@NonNull Application application) {
        super(application);

        Bmob.initialize(application, "d2a6fff57599e898e32fa2612a3597fe");
        repository=new StoryRepository(application);
        allUsers=repository.getAllUsers();
        allStories=repository.getAllStories();

    }

    public LiveData<List<User>> getAllUsers() {
        return allUsers;
    }
    public LiveData<List<Story>> getAllStories() {
        return allStories;
    }
    public Story getStories(String storytitle){
        List<Story> list=allStories.getValue();
        if(list==null)
            return null;
        for(Story story: list){
            if(story.getTitle().equals(storytitle))
                return story;
        }
        return null;
    }

    public LiveData<List<Purchased>> getPurchased(String username){
        return repository.getPurchased(username);
    }
    public User getUser(String username){
        List<User> list=allUsers.getValue();
        if(list==null)
            return null;
        for (User user: list){
            if(user.getName().equals(username)){
                return user;
            }
        }
        return null;
    }

    public LiveData<User> getRememberMe(){
        return repository.getRememberMe();
    }
    public void eraseRememberMe(){
        repository.eraseRememberMe();
    }

    public void insert(User user){
        repository.insert(user);
    }
    public void insert(Story story){repository.insert(story);}
    public void insert(Actor actor){repository.insert(actor);}
    public void insert(RememberMe rememberMe){repository.insert(rememberMe);}
}
